const app = getApp();
let richText = null; //解决方案富文本编辑器实例
Page({
    data: {
        id: '',
        question: null,
        showComment: false,
        isComment: true,
        message:'',
        commentId: '',
        replyuserId: '',
        // TODO 获取用户全局id
        // userId : app.globalData.userInfo.id;
        userId: '120235415',
        height: null,
        answerTitle: '',
        readOnly: false,
        answerDetail: '',
        isShowAnswer: false,
    },
    onLoad: function (options) {
        this.setData({
            id: options.id
        });
        this.setData({
            question: null
        });
        this.getQuestionById(this.data.id);
    },
    onShow: function () {

    },

    saveAnswer: function () {
        let that = this;
        let answer = {
            questionId: that.data.id,
            //TODO 用户名
            createBy: 'test',
            title: that.data.answerTitle,
            detail: that.data.answerDetail
        }
        wx.request({
            url: app.globalData.serverUrl + 'answer/saveAnswer',
            method: 'post',
            data: JSON.stringify(answer),
            success: function (res) {
                if (res.data.status == 200){
                    let question = {
                        id: app.globalData.questionId
                    }
                    that.setData({
                        isShowAnswer: false,
                        answerDetail: '',
                        answerTitle:''
                    })
                }
            }
        })
        console.log(answer)
    },
    showAnswer(){
        let that = this;
        that.setData({
            isShowAnswer: true
        })
    },
    closeAnswer(){
        let that = this;
        that.setData({
            isShowAnswer: false
        })
    },
    /*
    * 富文本开始
    * */
    // 编辑器初始化完成时触发，可以获取组件实例
    onEditor2Ready() {
        console.log('[onEditorReady callback]')
        richText = this.selectComponent('#answerRichText'); //获取组件实例
    },

    //设置富文本内容
    setContents(rechtext) {
        this.editorCtx.setContents({
            html: rechtext,
            success: res => {
                console.log('[setContents success]', res)
            }
        })
    },

    //撤销
    undo() {
        console.log('[undo callback]')
    },

    //恢复
    restore() {
        console.log('[restore callback]')
    },

    //清空编辑器内容
    clear() {
        this.editorCtx.clear({
            success: res => {
                console.log("[clear success]", res)
            }
        })
    },

    //清空编辑器事件
    clearBeforeEvent(){
        console.log('[clearBeforeEvent callback]')
        wx.showModal({
            cancelText: '取消',
            confirmText: '确认',
            content: '确认清空编辑器内容吗？',
            success: (result) => {
                if(result.confirm){
                    richText.clear();
                }
            },
            fail: (res) => {},
        })
    },

    //清空编辑器成功回调
    clearSuccess(){
        console.log('[clearSuccess callback]')
    },

    //清除当前选区的样式
    removeFormat() {
        this.editorCtx.removeFormat();
    },

    //插入图片
    insertImageEvent() {
        let that = this;
        wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success: res => {
                let path = res.tempFilePaths[0];
                //调用子组件方法，图片应先上传再插入，不然预览时无法查看图片。
                // tempFilePath可以作为img标签的src属性显示图片
                wx.uploadFile({
                    url: app.globalData.serverUrl + 'qiniu', //仅为示例，非真实的接口地址
                    filePath: path,
                    name: 'file',
                    success(res) {
                        let data = JSON.parse(res.data)
                        path = data.data.link;
                        if (that.data.hasAnswer) {
                            answer.insertImageMethod(path).then(res => {
                                console.log('[insert image success callback]=>', res)
                            }).catch(res => {
                                console.log('[insert image fail callback]=>', res)
                            });
                        } else {
                            richText.insertImageMethod(path).then(res => {
                                console.log('[insert image success callback]=>', res)
                            }).catch(res => {
                                console.log('[insert image fail callback]=>', res)
                            });
                        }
                    }
                })
            }
        })
    },

    //保存，获取编辑器内容
    getEditorContent(res) {
        let that = this;
        let {
            value
        } = res.detail;
        wx.showToast({
            title: '获取编辑器内容成功',
            icon: 'none',
        })
        that.setData({
            answerDetail: value.html
        })
        console.log('[getEditorContent callback]=>', value)
    },

    //show文本工具栏
    showTextTool() {
        this.setData({
            textTool: !this.data.textTool
        })
    },

    //编辑器聚焦时触发
    bindfocus(res) {
        let {
            value
        } = res.detail;
        // console.log('[bindfocus callback]=>', value)
    },

    //编辑器失去焦点时触发
    bindblur(res) {
        let {
            value
        } = res.detail;
        // console.log('[bindblur callback]=>', value)
    },

    //编辑器输入中时触发
    bindinput(res) {
        let {
            value
        } = res.detail;
        // console.log('[bindinput callback]=>', value)

        app.data.richTextContents = value.detail.html;
    },
    /*
    * 富文本结束
    * */
    toBig: function (option) {
        let id = option.currentTarget.dataset.id;
        document.getElementById(id);
    },
    getQuestionById(id) {
        let that = this;
        console.log(id)
        wx.request({
            url: app.globalData.serverUrl + "question/getByQuestion",
            method: 'post',
            data:{
                id : id
            },
            success: function (res) {
                // console.log(res.data.data)
                let data = res.data.data.data;
                that.setData({
                    question: data
                });
                that.onEditorReady();
            }
        })
    },
    onEditorReady() {
        let that = this;
        console.log(that.data.question)
        wx.createSelectorQuery().select('#editor').context(res => {
            this.editorCtx = res.context;
            this.editorCtx.setContents({
                html: that.data.question.detail,
                success: res => {
                    console.log('[setContents success]')
                }
            })
        }).exec()
    },
    onEditorReady1: function (option){
        let id = option.currentTarget.dataset.id;
        wx.createSelectorQuery().select('#editor'+id).context(res => {
            this.editorCtx = res.context;
            this.editorCtx.setContents({
                html: option.currentTarget.dataset.detail,
                success: res => {
                    console.log('[setContents success]')
                }
            })
        }).exec();
    },
    showComment: function () {
        this.setData({
            showComment: true,
            isComment: true
        })
    },
    closeComment(){
        this.setData({
            showComment: false,
            isComment: false
        });
    },
    saveComment: function () {
        let that = this;
        if (that.data.isComment) {
            let comment = this.data.message;
            let questionId = this.data.id;
            let remark1 = 0;
            // TODO 获取用户全局id
            // let userId = app.globalData.userInfo.id;
            let userId = 'beab638ec7d9ca783474c4525cef6614';
            let param = {
                detail: comment,
                questionId: questionId,
                remark1: remark1,
                userId: userId
            }
            wx.request({
                url: app.globalData.serverUrl + "comment",
                method: "post",
                data: JSON.stringify(param),
                success: function (res) {
                    if (res.data.status == 200) {
                        wx.showToast({
                            title: res.data.data.success,
                            icon: 'success',
                            duration: 2000//持续的时间
                        })
                        that.getQuestionById(that.data.id);
                        that.setData({
                            showComment: false,
                            message: ''
                        });
                    } else {
                        wx.showToast({
                            title: res.data.data.msg,
                            icon: 'none',
                            duration: 2000//持续的时间
                        });
                        that.setData({
                            showComment: false,
                            message: ''
                        });
                    }
                }
            })
        } else {
            // console.log(that.data.commentId)
            that.addReply();
        }
    },
    showReply: function (option) {
        this.setData({
            commentId: option.currentTarget.dataset.id,
            replyuserId: option.currentTarget.dataset.replyuserId,
            // TODO 获取用户全局id
            // userId : app.globalData.userInfo.id;
            userId: '120235415',
            message:'',
            showComment: true,
            isComment: false
        })
        // let commentId = option.id;
        // let replyuserId = option.replyuserId;
        // let userId = '120235415';
    },
    addReply: function () {
        let that = this;
        let commentId = that.data.commentId;
        let replyuserId = that.data.replyuserId;
        // TODO 用户id
        let userId = '120235415';
        let detail = that.data.message;
        let reply = {
            commentId : commentId,
            replyuserId : replyuserId,
            userId : userId,
            detail: detail
        }
        wx.request({
            url: app.globalData.serverUrl + 'commentReply',
            method: 'post',
            data: JSON.stringify(reply),
            success: function (res){
                if (res.data.status == 200){
                    wx.showToast({
                        title: res.data.data.success,
                        icon: 'success',
                        duration: 2000//持续的时间
                    })
                    that.getQuestionById(that.data.id);
                    that.setData({
                        showComment: false,
                        message: ''
                    });
                } else {
                    wx.showToast({
                        title: res.data.data.success,
                        icon: 'success',
                        duration: 2000//持续的时间
                    })
                }
            }
        });
    },
    addLike: function () {
        let that = this;
        let like = {
            targetId: that.data.id,
            //TODO 用户名
            createBy: 'test',
            type: '0'
        }
        wx.request({
            url: app.globalData.serverUrl + "likes",
            method: "post",
            data: JSON.stringify(like),
            success: function (res) {
                // if (res.data.data.)
                if(res.data.status == 200) {
                    wx.showToast({
                        title: res.data.data.success,
                        icon: 'success',
                        duration: 2000//持续的时间
                    });
                    that.setData({
                        "question.likeCount": that.data.question.likeCount+1
                    })
                    // that.search();
                } else {
                    wx.showToast({
                        title: res.data.msg,
                        icon: 'none',
                        duration: 2000//持续的时间
                    })
                }
            }
        })
    }
});
